package com.frame.auth.resource.security.config;

import com.frame.auth.resource.security.common.SecurityRequest;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @auther zhangwj
 * @date 2021/4/12 下午1:44
 */
public class AuthBearerTokenExtractor extends BearerTokenExtractor {

    private SecurityRequest securityRequest;

    public AuthBearerTokenExtractor(SecurityRequest securityRequest) {
        this.securityRequest = securityRequest;
    }

    @Override
    protected String extractHeaderToken(HttpServletRequest request) {
        Enumeration<String> headers = request.getHeaders(securityRequest.getHeaders());
        String value;
        do {
            if (!headers.hasMoreElements()) {
                return null;
            }
            value = headers.nextElement();
        } while (!value.toLowerCase().startsWith(securityRequest.getValue().toLowerCase()));

        String authHeaderValue = value.substring(securityRequest.getValue().length()).trim();
        request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, value.substring(0, securityRequest.getValue().length()).trim());
        int commaIndex = authHeaderValue.indexOf(44);
        if (commaIndex > 0) {
            authHeaderValue = authHeaderValue.substring(0, commaIndex);
        }

        return authHeaderValue;
    }
}
